const { exec } = require('child_process');
const path = require('path');
const fs = require('fs');

// 伪实现：实际应调用snarkjs命令行或wasm生成proof
exports.generateProof = (creditScore, threshold) => {
  return new Promise((resolve, reject) => {
    // 1. 生成input.json
    const input = { creditScore, threshold };
    const inputPath = path.join(__dirname, '../../circuits/build/input.json');
    fs.writeFileSync(inputPath, JSON.stringify(input));

    // 2. 调用snarkjs生成proof（此处为伪代码，实际需配置好路径和命令）
    const proofPath = path.join(__dirname, '../../circuits/build/proof.json');
    const publicPath = path.join(__dirname, '../../circuits/build/public.json');
    const cmd = `snarkjs groth16 prove ../../circuits/build/credit_final.zkey ${inputPath} ${proofPath} ${publicPath}`;

    exec(cmd, { cwd: path.join(__dirname, '../../circuits/build') }, (err, stdout, stderr) => {
      if (err) {
        return reject(new Error('Proof generation failed: ' + stderr));
      }
      // 3. 读取proof.json
      try {
        const proof = JSON.parse(fs.readFileSync(proofPath));
        resolve(proof);
      } catch (e) {
        reject(new Error('Failed to read proof: ' + e.message));
      }
    });
  });
}; 